import httpx
from typing import Optional, Dict, Any
from app.utils.logging import log_message


class BaseHTTPClient:
    def __init__(self, base_url: str):
        self.base_url = base_url

    async def _request(
            self,
            method: str,
            *,
            params: Optional[Dict] = None,
            json: Optional[Dict] = None,
            headers: Optional[Dict] = None,
            timeout: float = 30.0
    ) -> Any:
        url = f"{self.base_url}"
        try:
            async with httpx.AsyncClient() as client:
                response = await client.request(
                    method,
                    url,
                    params=params,
                    json=json,
                    headers=headers,
                    timeout=timeout
                )
                response.raise_for_status()
                return response.json()

        except httpx.HTTPStatusError as e:
            log_message(
                "http_request_error",
                {
                    "url": url,
                    "status_code": e.response.status_code,
                    "error": e.response.text
                },
                level="error"
            )
            raise ValueError(f"API请求失败: {e.response.text}")
        except Exception as e:
            log_message(
                "http_request_error",
                {"url": url, "error": str(e)},
                level="error"
            )
            raise ValueError(f"请求过程中发生错误: {str(e)}")
